#include"mystdio.h"
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<unistd.h>

const char* toString(int flag)
{
    if(flag & NONE_FLUSH)
    {
        return "NONE";
    }
    else if(flag & LINE_FLUSH)
    {
        return "LINE";
    }
    else if(flag & FULL_FLUSH)
    {
        return "FULL";
    }
    else 
    {
        return "unknown";
    }
}

void DebugPrint(myFILE* fp)
{
    printf("outbuff:%s\n",fp->outbuff);
    printf("fd:%d\n",fp->fileno);
    printf("pos:%d\n",fp->pos);
    printf("cap:%d\n",fp->cap);
    printf("flush_mode:%s\n",toString(fp->flush_mode));
}


myFILE* my_open(const char* pathname,const char* mode)
{
    int flag = 0;
    if(strcmp(mode,"r") == 0)
    {
        flag |= O_RDONLY; 
    }
    else if(strcmp(mode,"w") == 0)
    {
        flag |= (O_WRONLY|O_CREAT|O_TRUNC);
    }
    else if(strcmp(mode,"a") == 0)
    {
        flag |= (O_WRONLY|O_CREAT|O_APPEND);
    }
    else{
        return NULL;
    }

    myFILE* fp = (myFILE*)malloc(sizeof(myFILE));
    if(fp == NULL) return NULL;

    int fd = 0;
    if(flag & O_RDONLY)
    {
        fd = open(pathname,flag);
    }
    else{
        umask(0);
        fd = open(pathname,flag,0666);
    }
    if(fd < 0)   return NULL;

    fp->fileno = fd;
    fp->pos = 0;
    fp->cap = SIZE;
    fp->flush_mode = LINE_FLUSH;
    return fp;
}

void my_fflush(myFILE* fp)
{
    if(fp->pos == 0) return ;
    write(fp->fileno,fp->outbuff,fp->pos);
    fp->pos = 0;
}
int my_fwrite(myFILE* fp,const char* s,int size)
{
    memcpy(fp->outbuff+fp->pos,s,size);
    fp->pos += size;
    if((fp->flush_mode & LINE_FLUSH) && fp->outbuff[fp->pos-1] == '\n')
    {
        my_fflush(fp);
    }
    else if(fp->flush_mode & FULL_FLUSH)
    {
        my_fflush(fp);
    }
    return size;
}

void my_close(myFILE* fp)
{
    my_fflush(fp);
    close(fp->fileno);
    free(fp);
}
